<?php
/**
*
*上传相片，上传头像
*
**/
include "config.php";
define('UPLOAD_PHOTO_MAX_NUMS', 20);//最多上传相片的张数
$act = $_REQUEST['act'];
logWrite(THIS_PAGE);
error_reporting(0);

/**
 * 上传相片
 */
if($act=='photo'){
	$uid     = trim(@$_REQUEST['uid']);
	#$pwd      = trim($_REQUEST['pwd']);
	$album_id = trim(@$_REQUEST['album_id']);
	$photo_id = trim(@$_REQUEST['photo_id']);
	//$pname    = trim(iconv('gb2312','UTF-8',$_GET['pname']));
	$pname = '';
	$cover    = trim(@$_REQUEST['cover']);
	$desc     = trim(@$_REQUEST['desc']);
	
	
	$sql = "SELECT uid FROM t_user WHERE uid = '$uid'";
	$row = $db->getRow($sql);
	if(!$row){
		die('囧！用户不存在！');
	}
	#查询历史相片记录
	$sql = "SELECT photo_rec FROM t_user_record WHERE uid = '".$row['uid']."'";
	$photo_rec = $db->getOne($sql);
	#如果存在相片和相册记录，解密为数组格式
	if ($photo_rec){
		$photo_rec = json_decode($photo_rec,true);
		#如果没有相片记录则初始化一个默认相片记录
	    if ( !array_key_exists('p', $photo_rec)){       
            $photo_rec['p'] =array("last_rec_id"=>0,"list"=>array());
        }else {
            if (count($photo_rec['p']['list'])>=UPLOAD_PHOTO_MAX_NUMS){
                die('囧！只能上传20张相片哦！');                
            }
        }	
	}else{	
		$photo_rec = array("p"=>array("last_rec_id"=>0,"list"=>array()));	
	}
	#如果没有相册记录，则初始化一个默认相册
	if ( !@key($photo_rec['a'])){
		$photo_rec['a']=array(
			'last_rec_id'=>1,
			'list'=>array(
						array(
								'rec_id'=>1,
								'aname'=>'默认相册',
								'cover'=>0,
								'role'=>0, 
								'desc'=>'',
								'timeline'=>time())
			));
		$album_id = 1;
	}
	#定义一个变量为相片记录
	$list = $photo_rec['p']['list'];
	
	$newlist = $list;
	#如果是修改相片信息，则先删除要修改的相片记录，再赋值一个新记录
	if ($photo_id){
		foreach($list as $k=>$v){
			if($v['album_id']==$album_id && $v['rec_id']==$photo_id){
				unset($newlist[$k]);			
			}
		}
		sort($newlist);
		
	}else{
		$photo_id = $photo_rec['p']['last_rec_id']+1;
		if (!$list){//如果没有相片记录设置默认封面
			$photo_rec['a']['list'][0]['cover'] = $photo_id;
		}	
	}
	#定义一个新记录并添加到历史记录中
	$new_rec = array(
	"rec_id"=>$photo_id+0,
	"album_id"=>$album_id+0,
	"c_true"=>0,
	"c_false"=>0,
	"c_count"=>0,
	"type"=>'none',
//	"pname"=>$pname,
//	"deac"=>$desc,
	"timeline"=>time());
	
	array_push($newlist,$new_rec);
	
	$photo_rec['p']['list'] = $newlist;
	$photo_rec['p']['last_rec_id'] = $photo_id;
	
	#如果是设为封面，则设置当前相片为封面
	if($cover){
		foreach($photo_rec['a']['list'] as $k=>$v){
			if ($v['rec_id']==$album_id){
				$photo_rec['a']['list'][$k]['cover']=$photo_id+0;			
				break;
			}
		}
	} 
	
	#上传相片，并存到数据库中
	$rs = flashUpload($row['uid'],'photo',$photo_id);
	//$rs = uploadPic($row['uid'],'photo',$photo_id);
	if ($rs['res']===true){		
		$json = json_encode($photo_rec);
		$json = mysql_escape_string($json);
		$sql = "UPDATE t_user_record SET photo_rec = '$json' WHERE uid = '".$row['uid']."'";
		$db->query($sql);
		echo $photo_id;
		//;
		$str = 'up_photo {"uid":'.$uid.',"type":2}';
		socketData($server, $port,$str);
		die();
	}else{
		$arr = $rs;
	}
	die('囧！上传失败！');
}

/**
 * 上传头像
 */
if ($act=='head'){
	$uid     = trim($_REQUEST['uid']);
	#$pwd      = trim($_REQUEST['pwd']);	
	$sql = "SELECT * FROM t_user WHERE uid = '$uid' ";
	$row = $db->getRow($sql);
	if(!$row){
		$arr = array('res'=>'user_is_null','msg'=>'用户不存在');
		die(json_encode($arr));
	}	
	
	$rs = flashUpload($row['uid'],'head',$photo_id);
	if ($rs['res']===true){
		$sql = "UPDATE t_user SET is_upload_head = 1,upload_head_time='".date("Y-m-d H:i:s")."' WHERE uid = '".$row['uid']."'";
		$db->query($sql);
		//die(WWW_HOST.'res/photo/'.$rs['path']);
		if ($row['is_upload_head']=='0'){//首次上传头像增加游戏数值
			$str = 'up_photo {"uid":'.$uid.',"type":1}';
			socketData($server, $port,$str);
		}
	}else{
		$arr = $rs;
	}	
	echo json_encode($arr);
	die();
} 


/**
 * 
 * flash上传文件
 * @param integer $userid
 * @param string $type
 * @param integer $photo_id
 */
function flashUpload($userid,$type='head',$photo_id=null){
	$img = file_get_contents("php://input");
	if(!$img){
		$arr=array('res'=>'no_file');
		die(json_encode($arr));
	}	
	//获取上传的文件的信息
	$extname = 'png';
	$user_zone = intval($userid / 10000);
	$savePath = $user_zone. "/" . $userid . "/";
	$newPath = UPLOAD_DIR . $savePath;
	if ($type=='head'){ 
		$newfilename = $type."." . $extname;
	}else{
		$newfilename =  $photo_id . "." . $extname;
	}
	CreateFolder($newPath); //建立文件夹
	logWrite($newPath.$newfilename);
	file_put_contents($newPath.$newfilename, $img);
	//echo $newPath;
//	$rs = UploadFile($fileInputName, $newPath, $newfilename);
	return array('res'=>true,'path'=>$savePath.$newfilename);
	
}

function uploadPic($userid,$type='head',$photo_id='')
{
	$fileInputName = "file";
	$files = $_FILES[$fileInputName];
	$errors = $files["error"];
	$name = $files['name'];
	echo $errors;
	if($errors == UPLOAD_ERR_NO_FILE )
	{
		die("fatal:no attachments");  //没有文件上传
	}
	if($errors != UPLOAD_ERR_OK)
	{
		die("fatal:upload attachments error"); //出错
	}
	//获取上传的文件的信息
	$name = $files['name'];
	$extname = GetFileExtName($name);
	$user_zone = intval($userid / 10000);
	$savePath = $user_zone. "/" . $userid . "/";
	$newPath = UPLOAD_DIR . $savePath;
	if ($type=='head'){ 
		$newfilename = $type."." . $extname;
	}else{
		$newfilename =  $photo_id . "." . $extname;
	}
	//echo $newPath;
	$rs = UploadFile($fileInputName, $newPath, $newfilename);	
	if($rs===true){
		return array('res'=>true,'path'=>$savePath.$newfilename);
	}else {
		return array('res'=>$rs);
	}
}
